<?php
include_once '../icloud_files/system/DB.php';


class UserModel extends DB {

    public $messages, $user_data = array(), $page_title, $new_password, $email_data, $dealer_list;
/* ------------------------------------------------------------------------------------------------- */


    public function register_user($data, $pic) {
        //input norm, valid, checks
        foreach ($data as $k => $v) {
            $this->user_data[$k] = $this->db_connection->real_escape_string(trim($v));
        }

        if($this->user_data['account_type'] != 'dealer') {
            $this->user_data['account_type'] = 'member';
        }

        if(!filter_var($this->user_data['email'], FILTER_SANITIZE_EMAIL)) {
            $this->messages[] = 'Please enter a valid email.';
        }

        if(mb_strlen($this->user_data['pass1']) < 5) {
            $this->messages[] = 'The password must be at least 5 symbols.';
        }

        if($this->user_data['pass1'] !== $this->user_data['pass2']) {
            $this->messages[] = 'Passwords do not match.';
        }

        if(mb_strlen($this->user_data['username']) < 2 || mb_strlen($this->user_data['first_name']) < 2 ||
            mb_strlen($this->user_data['surname']) < 2) {
            $this->messages[] = 'Please enter at least 2 symbols for your username/company name, first name and surname.';
        }

        if(mb_strlen($this->user_data['city']) < 2) {
            $this->messages[] = 'Please enter at least 2 symbols for the city.';
        }

        if(empty($this->user_data['state'])) {
            $this->messages[] = 'Please select a state.';
        }

        if(mb_strlen($this->user_data['phone']) < 5) {
            $this->messages[] = 'Please enter a valid phone number including city/country prefix.';
        }

        $query = $this->db_connection->query("SELECT * FROM users WHERE email='".$this->user_data['email']."'");
        if($query->num_rows > 0) {
            $this->messages[] = 'Email is already taken.';
        }

        $query1 = $this->db_connection->query("SELECT * FROM users WHERE username='".$this->user_data['username']."'");
        if($query1->num_rows > 0) {
            $this->messages[] = 'Username is already taken, please choose another one.';
        }

        if((int)$this->user_data['tac'] != 1) {
            $this->messages[] = 'In order to use our services you need to read and accept our Advertiser Terms and Conditions first.';
        }

        if(count($this->messages) > 0) {
            return $this;
        }

        //add user to database
        $result = $this->db_connection->query("INSERT INTO users (account_type, email, password, username, first_name,
            surname, phone, city, postal_code, state) VALUES (
            '".$this->user_data['account_type']."',
            '".$this->user_data['email']."',
            '".sha1(sha1($this->user_data['pass1']))."',
            '".$this->user_data['username']."',
            '".$this->user_data['first_name']."',
            '".$this->user_data['surname']."',
            '".$this->user_data['phone']."',
            '".$this->user_data['city']."',
            '".$this->user_data['postal_code']."',
            '".$this->user_data['state']."')");

        if($result) {
            //upload company logo to server and add link to database
            if($pic['company_logo']['error'] === UPLOAD_ERR_OK) {
                $user_id = $this->db_connection->insert_id;
                $tmp_path = $pic['company_logo']['tmp_name'];
                $dir =  'img/views/user_data/seller_id_'.$user_id.'/';
                if(!is_dir($dir)) {
                    mkdir($dir, 0777, true);
                }
                $new_path = $dir.'company_logo.'.pathinfo($pic['company_logo']['name'], PATHINFO_EXTENSION);

                if(!move_uploaded_file($tmp_path, $new_path)) {
                    $this->messages[] = '1The company logo could not be uploaded. Please try again later.';
                } else {
                    $this->db_connection->query("UPDATE users SET company_logo='$new_path'
                        WHERE user_id={$user_id}");

                    if($this->db_connection->affected_rows !== 1) {
                        $this->messages[] = 'The company logo could not be uploaded. Please try again later.';
                    }
                }
            }

            $this->success = true;
            $this->messages[] = 'You have registered successfully with email: '.$this->user_data['email'].
                '. You can login now. Enjoy using the platform.';
        } else {
            $this->messages[] = 'There has been a problem with your request. We are sorry for the inconvenience, please try again later.';
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function get_seller($user_id) {
        $user_id = (int)$user_id;

        $query = $this->db_connection->query("SELECT * FROM users WHERE user_id='".$user_id."'");
        if($query->num_rows == 1) {
            $this->user_data = $query->fetch_assoc();

        } else {
            $this->messages[] = 'Internal error. Please try again later.';
        }
        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function login_user($email, $pass) {
        $email = $this->db_connection->real_escape_string(trim($email));
        $pass = sha1(sha1($this->db_connection->real_escape_string(trim($pass))));

        $query = $this->db_connection->query("SELECT * FROM users WHERE email='".$email."' AND password='".$pass."'");
        if($query->num_rows == 1) {
            $this->user_data = $query->fetch_assoc();

        } else {
            $this->messages[] = 'Invalid username or password';
        }
        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function reset_password($email, $check1, $check2) {
        $this->user_data['email'] = $this->db_connection->real_escape_string(trim($email));
        $check1 = $this->db_connection->real_escape_string(trim($check1));
        $check2 = $this->db_connection->real_escape_string(trim($check2));

        if($check1 != $check2) {
            $this->messages[] = 'Invalid number check summation. Please try again.';
            return $this;
        }

        $query = $this->db_connection->query("SELECT * FROM users WHERE email='".$this->user_data['email']."'");
        if($query->num_rows == 1) {
            $this->user_data = $query->fetch_assoc();
            //generate new password
            $this->new_password = $this->random_pwd();
            $result = $this->db_connection->query("UPDATE users SET
                password='".sha1(sha1($this->new_password))."' WHERE email='".$this->user_data['email']."'");

            if(!$result) {
                $this->messages[] = 'An error has occurred. Sorry for the inconvenience, please try again later.';
            } else {
                $msg_body = "<!DOCTYPE html><html><head></head><body>
                    Dear ".$this->user_data['username'].",<br/><br/>
                    This is an automated password reset message from the Ahimeh Cars site
                    <a href='".$_SERVER['HTTP_HOST']."'>".$_SERVER['HTTP_HOST']."</a>.<br/>
                    Your new password is: ".$this->new_password."<br/><br/>
                    Thanks, <br/>
                    the Ahimeh Cars site admin</body></html>";
                $msg_title = "Ahimeh Cars Website: Password reset for user: ".$this->user_data['username'];
                $this->send_email($this->user_data['email'], $msg_title, $msg_body);
            }

        } else {
            $this->messages[] = 'An error has occurred. Sorry for the inconvenience, please try again later.';
        }
        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function random_pwd() {
        $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }
/* ------------------------------------------------------------------------------------------------- */


    public function send_email($email, $title, $body, $headers = '') {
        $body = wordwrap($body, 70, "\r\n");
        $mailed = @mail($email, $title, $body, 'Content-type: text/html; charset=utf-8' . "\r\n".$headers);

        if($mailed) {
            $this->messages[] = 'The message has been sent successfully.';
            $this->email_data['success'] = true;
        } else {
            $this->messages[] = 'The message could not be sent at this time, please try again later.';
        }
        return $this;

    }
/* ------------------------------------------------------------------------------------------------- */


    public function contact_form($data) {
        $this->email_data['user_name'] = htmlspecialchars(trim($data['user_name']));
        $this->email_data['user_state'] = htmlspecialchars(trim($data['user_state']));
        $this->email_data['user_city'] = htmlspecialchars(trim($data['user_city']));
        $this->email_data['user_email'] = htmlspecialchars(trim($data['user_email']));
        $this->email_data['user_phone'] = htmlspecialchars(trim($data['user_phone']));
        $this->email_data['user_comment'] = htmlspecialchars(trim($data['user_comment']));

        //echo "<pre>" . print_r($this->email_data, true) . "</pre>";

        if(mb_strlen($this->email_data['user_name']) < 2) {
            $this->messages[] = 'Please enter at least 2 symbols for the name.';
        }

        if(!filter_var($this->email_data['user_email'], FILTER_SANITIZE_EMAIL)) {
            $this->messages[] = 'Please enter a valid email.';
        }

        if(mb_strlen($this->email_data['user_comment']) < 10) {
            $this->messages[] = 'Please enter at least 10 symbols for the comment.';
        }

        if(!count($this->messages) > 0) {
            //send email
            $email = 'viwanu@gmail.com';
            $title = 'Question from Ahimeh Cars Website';
            $msg_body = "<!DOCTYPE html><html><head></head><body>
                    MESSAGE FROM AHIMEH CARS WEBSITE (Contact form):<br/><br/>
                    User name: ".$this->email_data['user_name']."<br/>
                    User state: ".$this->email_data['user_state']."<br/>
                    User city: ".$this->email_data['user_city']."<br/>
                    User email: ".$this->email_data['user_email']."<br/>
                    User phone: ".$this->email_data['user_phone']."<br/>
                    User comment: ".$this->email_data['user_comment']."<br/><br/>
                    Ahimeh Cars Website, 2014 :
                    <a href='".$_SERVER['HTTP_HOST']."'>".$_SERVER['HTTP_HOST']."</a></body></html>";

            $headers = 'From: '.$this->email_data['user_email']."\r\n".
                'Reply-To: '.$this->email_data['user_email']."\r\n";

            $this->send_email($email, $title, $msg_body, $headers);

            if($this->email_data['success']) {
                unset($this->email_data);
            }
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function list_dealers($data) {
        //$_GET possible params : t (cgc cc asc), dealer_name , dealer_city , dealer_state


        //Dealer type filters
        if(isset($data['t'])) {
            $type = $this->db_connection->real_escape_string(trim($data['t']));
        }

        switch ($type) {
            case 'cgc':
                $type_filter = 'Car Grooming Center';
                break;

            case 'cc':
                $type_filter = 'Cars Customization';
                break;

            case 'asc':
                $type_filter = 'Auto Service Center';
                break;

            default:
                $type_filter = '%';
        }


        //Dealer name, city and state filters
        if(isset($data['dealer_name'])) {
            $dealer_name = '%'.$this->db_connection->real_escape_string(trim($data['dealer_name'])).'%';
        } else {
            $dealer_name = '%';
        }

        if(isset($data['dealer_city'])) {
            $dealer_city = '%'.$this->db_connection->real_escape_string(trim($data['dealer_city'])).'%';
        } else {
            $dealer_city = '%';
        }

        if(isset($data['dealer_state']) && $data['dealer_state'] !== '') {
            $dealer_state = $this->db_connection->real_escape_string(trim($data['dealer_state']));
        } else {
            $dealer_state = '%';
        }

        $query = $this->db_connection->query("SELECT center_id, business_type, company_name, city, state, phone, email, logo
            FROM auto_service_centers
            WHERE is_active=1 AND business_type LIKE '$type_filter' AND company_name LIKE '$dealer_name' AND
            city LIKE '$dealer_city' AND state LIKE '$dealer_state'
            ORDER BY date_added");

        if($query->num_rows > 0) {
            for($i=0; $row = $query->fetch_assoc(); $i++) {
                foreach ($row as $k => $v) {
                    $this->dealer_list[$i][$k] = $v;
                }
            }
        }

        return $this;

    }
/* ------------------------------------------------------------------------------------------------- */

}